package com.cy.pj.sys.config;

import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class shiroConfig {
    //@Bean public ShiroLoginFilter shiroLoginFilter(){ return new ShiroLoginFilter(); }
    @Bean
    public Authorizer authorizer(){
        return new ModularRealmAuthorizer();
    }
    /**
     * 将shiro中的注解RequiresPermissions放在控制层是需要配置此对象，
     * 并设置对控制层方法上的注解有效
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator=
                new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setUsePrefix(true);
        return advisorAutoProxyCreator;
    }

    @Bean
    public DefaultWebSessionManager sessionManager(){
        DefaultWebSessionManager sessionManager=
                new DefaultWebSessionManager();
        //session 的超时时间
        sessionManager.setGlobalSessionTimeout(1000*60*60);//1 个小时
//        sessionManager.setGlobalSessionTimeout(2*60*1000);//2 分钟
        //删除无效 session
        sessionManager.setDeleteInvalidSessions(true);
        //当客户端 cookie 被禁用是否要设置 url 重写
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }

    @Bean
    public RememberMeManager rememberMeManager(){
        CookieRememberMeManager rememberMeManager=
                new CookieRememberMeManager();
        SimpleCookie cookie=new SimpleCookie("rememberMe");
        cookie.setMaxAge(7*24*60*60);//设置cookie的生命周期
        rememberMeManager.setCookie(cookie);
        return rememberMeManager;
    }

    /**
     * 配置授权缓存管理器，缓存实现就是一个map
     * 配置 Shiro 中自带的 CacheManager 对象,此对象可以通过 Cache 缓存授权时获取到
     * 权限信息,下次再访问授权方法时不需要再查用户权限,这样可以减少数据库的访问压力,
     * 同时提高授权性能
     * @return
     */
    @Bean
    protected CacheManager shiroCacheManager() {
        return new MemoryConstrainedCacheManager();
    }
}
